<template>
  <div class="app-container">
    <div class="app-card">
      <!-- 搜索和工具栏 -->
      <div class="table-toolbar">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="团长姓名">
            <el-input v-model="queryParams.name" placeholder="请输入团长姓名" clearable size="small" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable size="small" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option :value="1" label="启用" />
              <el-option :value="0" label="禁用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <div>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
        </div>
      </div>
      
      <!-- 表格 -->
      <el-table v-loading="loading" :data="leaderList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="name" label="团长姓名" min-width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="address" label="提货点地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" icon="el-icon-s-order" @click="handleViewOrderStats(scope.row)">订单统计</el-button>
            <el-button type="text" icon="el-icon-money" @click="handleViewCommissionStats(scope.row)">佣金统计</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="!form.id" label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="团长姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入团长姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="提货点地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入提货点地址" />
        </el-form-item>
      
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 订单统计对话框 -->
    <el-dialog title="订单统计" :visible.sync="orderStatsVisible" width="600px" append-to-body>
      <div v-loading="statsLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="团长姓名">{{ orderStats.leaderName }}</el-descriptions-item>
          <el-descriptions-item label="总订单数">{{ orderStats.orderCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥ {{ orderStats.totalAmount || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="已完成订单">{{ orderStats.completedCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="已完成金额">¥ {{ orderStats.completedAmount || '0.00' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
    
    <!-- 佣金统计对话框 -->
    <el-dialog title="佣金统计" :visible.sync="commissionStatsVisible" width="600px" append-to-body>
      <div v-loading="statsLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="团长姓名">{{ commissionStats.leaderName }}</el-descriptions-item>
          <el-descriptions-item label="总佣金">¥ {{ commissionStats.totalCommission || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="已结算佣金">¥ {{ commissionStats.settledCommission || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="未结算佣金">¥ {{ commissionStats.unsettledCommission || '0.00' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLeaders, updateLeader, deleteLeader, changeLeaderStatus, getLeaderOrderStats, getLeaderCommissionStats, registerLeader } from '@/api/leader'

export default {
  name: 'Leader',
  data() {
    return {
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: '',
        phone: '',
        status: ''
      },
      // 总记录数
      total: 0,
      // 团长列表
      leaderList: [],
      // 加载状态
      loading: false,
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {
        id: undefined,
        username: '',
        password: '',
        name: '',
        phone: '',
        address: '',
        addressDetail: '',
        status: 1
      },
      // 表单校验规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入团长姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入提货点地址', trigger: 'blur' }
        ]
      },
      // 订单统计对话框显示状态
      orderStatsVisible: false,
      // 佣金统计对话框显示状态
      commissionStatsVisible: false,
      // 统计数据加载状态
      statsLoading: false,
      // 订单统计数据
      orderStats: {},
      // 佣金统计数据
      commissionStats: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取团长列表
    getList() {
      this.loading = true
      listLeaders({
        current: this.queryParams.current,
        size: this.queryParams.size,
        name: this.queryParams.name,
        phone: this.queryParams.phone,
        status: this.queryParams.status
      }).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.leaderList = response
          this.total = response.length
        } else {
          // 否则尝试获取list和total字段
          this.leaderList = response.list || response.records || []
          this.total = response.total || 0
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 搜索按钮点击事件
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.name = ''
      this.queryParams.phone = ''
      this.queryParams.status = ''
      this.queryParams.current = 1
      this.getList()
    },
    // 每页数量改变事件
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    // 页码改变事件
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 添加按钮点击事件
    handleAdd() {
      this.dialogTitle = '添加团长'
      this.form = {
        id: undefined,
        username: '',
        password: '',
        name: '',
        phone: '',
        address: '',
        addressDetail: '',
        status: 1
      }
      this.dialogVisible = true
    },
    // 编辑按钮点击事件
    handleUpdate(row) {
      this.dialogTitle = '编辑团长'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认删除该团长吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLeader(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 状态改变事件
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '禁用'
      this.$confirm(`确认${text}该团长吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeLeaderStatus(row.id, row.status).then(() => {
          this.$message.success(`${text}成功`)
        })
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    // 表单提交事件
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateLeader(this.form).then(() => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            registerLeader(this.form).then(() => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    // 查看订单统计
    handleViewOrderStats(row) {
      this.statsLoading = true
      this.orderStatsVisible = true
      this.orderStats = {}
      
      getLeaderOrderStats(row.id).then(response => {
        this.orderStats = response || {}
        this.statsLoading = false
      }).catch(() => {
        this.statsLoading = false
      })
    },
    // 查看佣金统计
    handleViewCommissionStats(row) {
      this.statsLoading = true
      this.commissionStatsVisible = true
      this.commissionStats = {}
      
      getLeaderCommissionStats(row.id).then(response => {
        this.commissionStats = response || {}
        this.statsLoading = false
      }).catch(() => {
        this.statsLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style> 